486D - Valid Sets - CodeForces Solution


dfs and similar dp math trees *2100

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
long long MOD;
int a[2005];
long long dp[2005];
int visited[2005];
int d;
vector<int> graph[2005] ;

void dfs(int current, int root){
    visited[current] = 1;
    for(auto u: graph[current]){
        if(visited[u] == 1){
            continue;
        }
        if(a[u] < a[root] || a[u] > a[root]+d){
            continue;
        }
        if((a[u] == a[root]) && u < root){
            continue;
        }
        dfs(u, root);
        dp[current] = dp[current]*(dp[u] + 1);
        dp[current] %= MOD;
    }
}

int main()
{
    // freopen("input.txt", "r", stdin);
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    MOD = 1e9+7;
    int n;
    cin>>d>>n;
    for(int i=1; i<=n; i++){
        cin>>a[i];
    }
    for(int i=1; i<n; i++){
        int u, v;
        cin>>u>>v;
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    
    long long res = 0;
    
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++){
            visited[j] = 0;
            dp[j] = 1;
        }
        dfs(i, i);
        res += dp[i];
        res %= MOD;
    }
    cout<<res;
    return 0;
}


Comments

Submit
0 Comments
More Questions

1582C - Grandma Capa Knits a Scarf
492A - Vanya and Cubes
217A - Ice Skating
270A - Fancy Fence
181A - Series of Crimes
1638A - Reverse
1654C - Alice and the Cake
369A - Valera and Plates
1626A - Equidistant Letters
977D - Divide by three multiply by two
1654B - Prefix Removals
1654A - Maximum Cake Tastiness
1649A - Game
139A - Petr and Book
1612A - Distance
520A - Pangram
124A - The number of positions
1041A - Heist
901A - Hashing Trees
1283A - Minutes Before the New Year
1654D - Potion Brewing Class
1107B - Digital root
25A - IQ test
785A - Anton and Polyhedrons
1542B - Plus and Multiply
306A - Candies
1651C - Fault-tolerant Network
870A - Search for Pretty Integers
1174A - Ehab Fails to Be Thanos
1169A - Circle Metro